package com.example.service.impl;

import com.example.common.Result;
import com.example.common.PageResult;
import com.example.entity.UserBalance;
import com.example.entity.User;
import com.example.mapper.UserBalanceMapper;
import com.example.mapper.UserMapper;
import com.example.service.UserBalanceService;
import com.example.util.JwtUserUtil;
import com.example.vo.UserBalanceVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class UserBalanceServiceImpl implements UserBalanceService {
    
    @Autowired
    private UserBalanceMapper userBalanceMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JwtUserUtil jwtUserUtil;
    
    @Override
    public Result<UserBalanceVO> getUserBalance(Long userId) {
        try {
            UserBalanceVO userBalanceVO = userBalanceMapper.selectVOByUserId(userId);
            if (userBalanceVO == null) {
                // 如果用户余额记录不存在，自动初始化
                initUserBalance(userId);
                userBalanceVO = userBalanceMapper.selectVOByUserId(userId);
            }
            return Result.success(userBalanceVO);
        } catch (Exception e) {
            log.error("获取用户余额失败，用户ID: {}", userId, e);
            return Result.error("获取用户余额失败");
        }
    }

    @Override
    public Result<UserBalanceVO> getMyBalance() {
        try {
            // 从当前请求上下文获取用户ID
            Long userId = jwtUserUtil.getCurrentUserIdFromContext();
            if (userId == null) {
                return Result.error("用户未登录");
            }

            return getUserBalance(userId);
        } catch (Exception e) {
            log.error("获取当前用户余额失败", e);
            return Result.error("获取用户余额失败");
        }
    }
    
    @Override
    @Transactional
    public Result<Void> initUserBalance(Long userId) {
        try {
            // 检查是否已存在余额记录
            UserBalance existingBalance = userBalanceMapper.selectByUserId(userId);
            if (existingBalance != null) {
                return Result.success();
            }
            
            // 创建新的余额记录
            UserBalance userBalance = new UserBalance();
            userBalance.setUserId(userId);
            userBalance.setBalance(BigDecimal.ZERO);
            userBalance.setFrozenBalance(BigDecimal.ZERO);
            userBalance.setTotalRecharge(BigDecimal.ZERO);
            userBalance.setTotalConsume(BigDecimal.ZERO);
            userBalance.setCreateTime(LocalDateTime.now());
            userBalance.setUpdateTime(LocalDateTime.now());
            userBalance.setDeleted(0);
            
            userBalanceMapper.insert(userBalance);
            log.info("初始化用户余额成功，用户ID: {}", userId);
            return Result.success();
        } catch (Exception e) {
            log.error("初始化用户余额失败，用户ID: {}", userId, e);
            return Result.error("初始化用户余额失败");
        }
    }
    
    @Override
    @Transactional
    public Result<Void> addBalance(Long userId, BigDecimal amount, String remark) {
        try {
            if (amount == null || amount.compareTo(BigDecimal.ZERO) <= 0) {
                return Result.error("金额必须大于0");
            }
            
            // 确保用户余额记录存在
            initUserBalance(userId);
            
            // 更新余额
            int result = userBalanceMapper.updateBalance(userId, amount, true);
            if (result > 0) {
                log.info("增加用户余额成功，用户ID: {}, 金额: {}, 备注: {}", userId, amount, remark);
                return Result.success();
            } else {
                return Result.error("增加用户余额失败");
            }
        } catch (Exception e) {
            log.error("增加用户余额失败，用户ID: {}, 金额: {}", userId, amount, e);
            return Result.error("增加用户余额失败");
        }
    }
    
    @Override
    @Transactional
    public Result<Void> subtractBalance(Long userId, BigDecimal amount, String remark) {
        try {
            if (amount == null || amount.compareTo(BigDecimal.ZERO) <= 0) {
                return Result.error("金额必须大于0");
            }
            
            // 检查余额是否充足
            Result<Boolean> checkResult = checkBalance(userId, amount);
            if (!checkResult.isSuccess() || !checkResult.getData()) {
                return Result.error("余额不足");
            }
            
            // 扣减余额
            int result = userBalanceMapper.updateBalance(userId, amount, false);
            if (result > 0) {
                log.info("扣减用户余额成功，用户ID: {}, 金额: {}, 备注: {}", userId, amount, remark);
                return Result.success();
            } else {
                return Result.error("扣减用户余额失败");
            }
        } catch (Exception e) {
            log.error("扣减用户余额失败，用户ID: {}, 金额: {}", userId, amount, e);
            return Result.error("扣减用户余额失败");
        }
    }
    
    @Override
    @Transactional
    public Result<Void> freezeBalance(Long userId, BigDecimal amount, String remark) {
        try {
            if (amount == null || amount.compareTo(BigDecimal.ZERO) <= 0) {
                return Result.error("金额必须大于0");
            }
            
            // 检查可用余额是否充足
            UserBalanceVO userBalance = userBalanceMapper.selectVOByUserId(userId);
            if (userBalance == null || userBalance.getAvailableBalance().compareTo(amount) < 0) {
                return Result.error("可用余额不足");
            }
            
            // 冻结余额
            int result = userBalanceMapper.updateFrozenBalance(userId, amount, true);
            if (result > 0) {
                log.info("冻结用户余额成功，用户ID: {}, 金额: {}, 备注: {}", userId, amount, remark);
                return Result.success();
            } else {
                return Result.error("冻结用户余额失败");
            }
        } catch (Exception e) {
            log.error("冻结用户余额失败，用户ID: {}, 金额: {}", userId, amount, e);
            return Result.error("冻结用户余额失败");
        }
    }
    
    @Override
    @Transactional
    public Result<Void> unfreezeBalance(Long userId, BigDecimal amount, String remark) {
        try {
            if (amount == null || amount.compareTo(BigDecimal.ZERO) <= 0) {
                return Result.error("金额必须大于0");
            }
            
            // 检查冻结余额是否充足
            UserBalanceVO userBalance = userBalanceMapper.selectVOByUserId(userId);
            if (userBalance == null || userBalance.getFrozenBalance().compareTo(amount) < 0) {
                return Result.error("冻结余额不足");
            }
            
            // 解冻余额
            int result = userBalanceMapper.updateFrozenBalance(userId, amount, false);
            if (result > 0) {
                log.info("解冻用户余额成功，用户ID: {}, 金额: {}, 备注: {}", userId, amount, remark);
                return Result.success();
            } else {
                return Result.error("解冻用户余额失败");
            }
        } catch (Exception e) {
            log.error("解冻用户余额失败，用户ID: {}, 金额: {}", userId, amount, e);
            return Result.error("解冻用户余额失败");
        }
    }
    
    @Override
    public Result<Boolean> checkBalance(Long userId, BigDecimal amount) {
        try {
            UserBalanceVO userBalance = userBalanceMapper.selectVOByUserId(userId);
            if (userBalance == null) {
                return Result.success(false);
            }

            boolean hasEnough = userBalance.getAvailableBalance().compareTo(amount) >= 0;
            return Result.success(hasEnough);
        } catch (Exception e) {
            log.error("检查用户余额失败，用户ID: {}, 金额: {}", userId, amount, e);
            return Result.error("检查用户余额失败");
        }
    }

    @Override
    public Result<Boolean> checkBalanceByAmount(Long userId, String amount) {
        try {
            BigDecimal checkAmount = new BigDecimal(amount);
            return checkBalance(userId, checkAmount);
        } catch (NumberFormatException e) {
            log.error("金额格式不正确，用户ID: {}, 金额: {}", userId, amount, e);
            return Result.error("金额格式不正确");
        } catch (Exception e) {
            log.error("检查用户余额失败，用户ID: {}, 金额: {}", userId, amount, e);
            return Result.error("检查用户余额失败");
        }
    }
    
    @Override
    public Result<List<UserBalanceVO>> getAllUserBalances() {
        try {
            List<UserBalanceVO> userBalances = userBalanceMapper.selectVOList(new UserBalance());
            return Result.success(userBalances);
        } catch (Exception e) {
            log.error("获取所有用户余额列表失败", e);
            return Result.error("获取用户余额列表失败");
        }
    }
    
    @Override
    public Result<PageResult<UserBalanceVO>> getUserBalancePage(int page, int size, String keyword) {
        try {
            int offset = (page - 1) * size;
            List<UserBalanceVO> userBalances = userBalanceMapper.selectPage(offset, size, keyword);
            
            // 这里简化处理，实际应该查询总数
            long total = userBalances.size();
            
            PageResult<UserBalanceVO> pageResult = new PageResult<>();
            pageResult.setRecords(userBalances);
            pageResult.setTotal(total);
            pageResult.setCurrent(page);
            pageResult.setSize(size);
            
            return Result.success(pageResult);
        } catch (Exception e) {
            log.error("分页查询用户余额失败，页码: {}, 大小: {}, 关键词: {}", page, size, keyword, e);
            return Result.error("分页查询用户余额失败");
        }
    }
    
    @Override
    @Transactional
    public Result<Void> updateBalanceAndTotalRecharge(Long userId, BigDecimal rechargeAmount) {
        try {
            // 确保用户余额记录存在
            initUserBalance(userId);
            
            int result = userBalanceMapper.updateBalanceAndTotalRecharge(userId, rechargeAmount);
            if (result > 0) {
                // 获取更新后的累计充值金额
                UserBalanceVO userBalance = userBalanceMapper.selectVOByUserId(userId);
                if (userBalance != null) {
                    // 更新会员等级
                    updateMemberLevel(userId, userBalance.getTotalRecharge());
                }
                
                log.info("更新用户余额和累计充值金额成功，用户ID: {}, 充值金额: {}", userId, rechargeAmount);
                return Result.success();
            } else {
                return Result.error("更新用户余额和累计充值金额失败");
            }
        } catch (Exception e) {
            log.error("更新用户余额和累计充值金额失败，用户ID: {}, 充值金额: {}", userId, rechargeAmount, e);
            return Result.error("更新用户余额和累计充值金额失败");
        }
    }
    
    @Override
    @Transactional
    public Result<Void> updateBalanceAndTotalConsume(Long userId, BigDecimal consumeAmount) {
        try {
            // 检查余额是否充足
            Result<Boolean> checkResult = checkBalance(userId, consumeAmount);
            if (!checkResult.isSuccess() || !checkResult.getData()) {
                return Result.error("余额不足");
            }
            
            int result = userBalanceMapper.updateBalanceAndTotalConsume(userId, consumeAmount);
            if (result > 0) {
                log.info("更新用户余额和累计消费金额成功，用户ID: {}, 消费金额: {}", userId, consumeAmount);
                return Result.success();
            } else {
                return Result.error("更新用户余额和累计消费金额失败");
            }
        } catch (Exception e) {
            log.error("更新用户余额和累计消费金额失败，用户ID: {}, 消费金额: {}", userId, consumeAmount, e);
            return Result.error("更新用户余额和累计消费金额失败");
        }
    }
    
    @Override
    @Transactional
    public Result<Void> updateMemberLevel(Long userId, BigDecimal totalRecharge) {
        try {
            if (userId == null || totalRecharge == null) {
                return Result.error("参数不能为空");
            }
            
            // 根据累计充值金额确定会员等级
            String newMemberLevel = "NORMAL"; // 默认普通用户
            
            if (totalRecharge.compareTo(new BigDecimal("1000")) >= 0) {
                newMemberLevel = "VIP1"; // 一级会员
            } else if (totalRecharge.compareTo(new BigDecimal("800")) >= 0) {
                newMemberLevel = "VIP2"; // 二级会员  
            } else if (totalRecharge.compareTo(new BigDecimal("500")) >= 0) {
                newMemberLevel = "VIP3"; // 三级会员
            }
            
            // 获取当前用户信息
            User user = userMapper.selectById(userId);
            if (user == null) {
                return Result.error("用户不存在");
            }
            
            // 如果等级没有变化，直接返回成功
            if (newMemberLevel.equals(user.getMemberLevel())) {
                return Result.success();
            }
            
            // 更新用户会员等级
            user.setMemberLevel(newMemberLevel);
            user.setUpdateTime(LocalDateTime.now());
            
            int result = userMapper.updateById(user);
            if (result > 0) {
                log.info("更新用户会员等级成功，用户ID: {}, 新等级: {}, 累计充值: {}", userId, newMemberLevel, totalRecharge);
                return Result.success();
            } else {
                return Result.error("更新用户会员等级失败");
            }
        } catch (Exception e) {
            log.error("更新用户会员等级失败，用户ID: {}, 累计充值: {}", userId, totalRecharge, e);
            return Result.error("更新用户会员等级失败");
        }
    }
}
